﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics.CodeAnalysis;


//Based heavily on http://laharsub.codeplex.com

namespace ThreeByte.ActiveDeck.Publish.Model
{
    [SuppressMessage("Microsoft.Design","CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", 
        Justification="ManualResetEvent is disposed in the End method")]
    public class CompletedAsyncResult<T> : IAsyncResult
    {
        public T Result { get; set; }
        AsyncCallback callback;
        object state;
        ManualResetEvent waitHandle = new ManualResetEvent(true);

        public CompletedAsyncResult(T result, AsyncCallback callback, object state)
        {
            this.Result = result;
            this.callback = callback;
            this.state = state;
            if (callback != null)
            {
                callback(this);
            }
        }

        public object AsyncState
        {
            get { return this.state; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get { return this.waitHandle; }
        }

        public bool CompletedSynchronously
        {
            get { return true; }
        }

        public bool IsCompleted
        {
            get { return true; }
        }

        public static void End(IAsyncResult result)
        {
            CompletedAsyncResult<T> r = result as CompletedAsyncResult<T>;
            if (r == null)
            {
                throw new InvalidOperationException("Invalid async result.");
            }
            r.waitHandle.Dispose();
        }
    }
}
